<?php

namespace App\Http\Controllers\Admin;

use Carbon\Carbon;
use App\Models\Shops;
use EasyWeChat\Payment\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Dotenv\Validator;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Excel;

class ShopController extends Controller
{
    /**
     * 店铺管理首页
     * @param Request $request
     * @param string $shop
     * @return $this|string
     */
    public  function index(Request $request,$shop=''){
        $where = array();
        if($shop){
            $where['shop_name'] = 'like %'.$shop.'%';
        }
        $shoplist = Shops::where($where)->paginate(10);
        if($request->isMethod('post')) {
            $rules= [
                'shop_id'     => 'required',
                'shop_name'   => 'required|max:255',
                'shop_info'   => 'required|max:255',
                'shop_secret' => 'required',
                'shop_date'   => 'required|date',
                'point'       => 'required'
            ];
            $msg = [
                'required'   => ':attribute为必填项',
                'unique'     => ':attribute为唯一',
                'digits'     => ':attribute为数值型并且长度不能超过10位',
                'max'        => ':attribute不符合要求',
                'shop_date.date'       => '开业时间格式不对'
            ];
            //dd($request->input());exit;
            //进行格式验证
            $validator = \Validator::make($request->input(), $rules, $msg);
            if ($validator->fails()) {
                $messages = $validator->errors();
                $result['msg'] = $messages->first();
                if(empty($result['msg']) && !empty(Shops::where('id',$request->shop_id)->get()))
                    $result['msg'] = '该店铺ID已存在，请刷新后再重新提交';
            }
            if(!empty($result)){
                $result['code'] = 400;
            }else{
                $shop = new Shops();
                $shop->id   = $request->shop_id;
                $shop->shop_name = $request->shop_name;
                $shop->shop_info = $request->shop_info;
                $shop->shop_secret = $request->shop_secret;
                $shop->open_time = $request->shop_date;
                $shop->state = 0;
                $shop_id = $shop->save();
                if($shop_id){
                    $result['code'] = 200;
                }
                $shop_key = generate_shop_key($shop_id+1);
            }
            return json_encode($result);
            //return view("admin.shop")->with('shoplist',$shoplist)->with('next_id',$shop_id+1)->with('shop_key',$shop_key)->with('message',$result);
        }else{

            $lastid   = Shops::orderBy('id' , 'desc')->firstOrFail();
            $next_id  = $lastid['id'] + 1;
            $shop_key = generate_shop_key($next_id);
            return view('admin.shop')->with('shoplist',$shoplist)
                                       ->with('next_id',$next_id)
                                       ->with('shop_key',$shop_key);
        }
    }

    /**
     * 店铺的详情
     * @param string $id 店铺ID
     * @return $this
     */
    public function show($id=''){
        if($id){
            $where['id'] = $id;
            $shopinfo = Shops::where($where)->first();
            $orderinfo = DB::table('orders')
                       ->where('shop_id',$id)
                       ->where('state','1')
                       ->select('orders.id','orders.order_num','orders.pay_time')
                       ->orderBy('id' , 'desc')
                       ->get()->toArray();
            $shop = array();
            if(!empty($orderinfo)){
                $skip = 0;
                foreach($orderinfo as $key => $val){
                    $info = DB::table('order_detail')
                        ->where('order_id',$val->id)
                        ->join('goods_nexus','goods_nexus.rfid','=','order_detail.rfid','left')
                        ->join('goods','goods.id','=','goods_nexus.goods_id','left')
                        ->select('goods.name')
                        ->get()->toArray();

                    $string = '';
                    foreach($info as $k => $v){
                        if(!empty($v)){
                            if($string){
                                if($v->name)
                                    $string = $string .','. $v->name;
                            }else{
                                $string = $v->name;
                            }
                        }
                    }
                    if($string && $skip <= 2){
                        $skip++;
                        $shop[$skip]['pay_time'] = $val->pay_time;
                        $shop[$skip]['name'] = $string;
                    }
                }
            }
                return view('admin/shop_show')->with('shopinfo',$shopinfo)->with('orderinfo',$shop);
        }else{
            $url = url('index');
            header('Location:',$url);
        }
    }
    /**
     * 修改店铺密匙.
     * @param string $id 店铺ID
     */
    public function change(Request $request){
        if($request->isMethod('post')){
            if($request->id){
                $shop_key = generate_shop_key($request->id);
                if($shop_key){
                    $result['code'] = 200;
                    $result['data'] = $shop_key;
                }else{
                    $result['code'] = 400;
                }
                return json_encode($result);
            }
            if($request->shop_id){
                $data = new Shops();
                $data->id          = $request->shop_id;
                $data->shop_secret = $request->shop_secret;
                $data->state       = $request->state;
                $data->point       = $request->point;
                $data->open_time   = $request->open_time;
                $data->shop_info   = $request->shop_info;
                $data->shop_name   = $request->shop_name;
                if($this->change_data($data)){
                    $result['code'] = 200;
                }else{
                    $result['code'] = 400;
                }
                return json_encode($result);
            }
        }
    }
    /**
     * 上传文件
     */
    public function upload(Request $request){
        $data = Excel::load($request->file('excel'), function($reader) {})->get()->toArray();
        //exce1表格中$ch_arr商品序号不能为空
        $sh_array = array();
        $new_data = array();
        foreach ($data[0] as $ite){
            reset($ite);
            foreach($ite as $key => $val){
                if($key == 'id' && !empty(intval($val))) {
                    $info = Shops::where('id', $val)->first();
                    if ($info) {
                        return json_encode(['status' => 0, 'msg' => 'excel表中的店铺id已经存在']);
                    }
                    $new_data['id'] = intval($val);
                }
                if($key == '店铺名称' && !empty($val)){
                    $new_data['shop_name'] = (string)$val;
                }
                if($key == '店铺信息' && !empty($val)){
                    $new_data['shop_info'] = (string)$val;
                }
                if($key == '店铺秘匙' && !empty($val)){
                    $new_data['shop_secret'] = (string)$val;
                }
                if($key == '店铺状态' && !empty($val)){
                    if($val == '营业中')
                        $new_data['state'] = 1;
                    else
                        $new_data['state'] = 0;
                }
                if($key == '店铺经纬度' && !empty($val)){
                    $new_data['point'] = (string)$val;
                }
                if($key == '开业时间' && !empty($val)){
                    $new_data['open_time'] = $val->toDateString();
                }
            }
            if(!empty($new_data)){
                $time = Carbon::now();
                $new_data['updated_at'] = $new_data['created_at'] = $time->toDateString();
                $id = Shops::insert($new_data);
                if(!$id){
                    return response()->json(['status' => 0, 'msg' => '该excel导入失败']);
                }
            }
        }
    return ['status'=>1,'msg'=>'导入成功'];
}


public function change_data($data){
    $old_data = Shops::where('id',$data->id)->first();
    $newdata['id']           = $data->id ? $data->id : $old_data->id;
    $newdata['shop_secret'] = $data->shop_secret ? $data->shop_secret : $old_data->shop_secret;
    $newdata['state']        = $data->state ? $data->state : $old_data->state;
    $newdata['point']        = $data->point ? $data->point : $old_data->point;
    $newdata['open_time']   = $data->open_time ? $data->open_time : $old_data->open_time;
    $newdata['shop_info']   = $data->shop_info ? $data->shop_info : $old_data->shop_info;
    $newdata['shop_name']   = $data->shop_name ? $data->shop_name : $old_data->shop_name;
    if($num = Shops::where('id',$data->id)->update($newdata)){
        return true;
    }else{
        return false;
        }
    }

    /**
     * 导出店铺模板
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function download() {
        return response()
        ->download(realpath(base_path('public')) . '/ShopModel.xlsx', "店铺导入表" . '.xlsx');
    }
}
